#ifndef AUDIOCAPTURE_H
#define AUDIOCAPTURE_H

#include <QObject>
#include <QAudioSource>
#include <QAudioSink>
#include <QAudioDevice>
#include <QAudioFormat>
#include <QMediaDevices>
#include <QFile>
#include <QBuffer>
#include <QDataStream>
#include <QTimer>
#include "audiotransmitter.h"

class AudioCapture : public QObject
{
    Q_OBJECT

public:
    explicit AudioCapture(QObject *parent = nullptr);
    ~AudioCapture();

    bool startCapture(const QString &deviceId, const QString &outputFilePath);
    void stopCapture();
    bool isCapturing() const { return m_isCapturing; }

    // 音频传输相关
    bool startTransmission(const QString &host = "localhost", quint16 port = 8766);
    void stopTransmission();
    bool isTransmitting() const { return m_transmitter ? m_transmitter->isTransmissionEnabled() : false; }
    
    // 传输配置
    void setTransmissionEnabled(bool enabled);
    void setTransmissionHost(const QString &host);
    void setTransmissionPort(quint16 port);
    void setTransmissionBufferSize(int size);
    void setTransmissionInterval(int intervalMs);
    void setTransmissionCompression(bool enabled);

signals:
    void captureStatusChanged(bool isCapturing);
    void captureError(const QString &error);
    
    // 传输相关信号
    void transmissionStatusChanged(bool isTransmitting);
    void transmissionError(const QString &error);
    void transmissionDataSent(qint64 bytesSent);
    void transmissionConnectionEstablished();
    void transmissionConnectionLost();

private slots:
    void onAudioDataReady();
    void onAudioSourceStateChanged(QAudio::State state);
    
    // 传输相关槽函数
    void onTransmissionStatusChanged(bool enabled);
    void onTransmissionError(const QString &error);
    void onTransmissionDataSent(qint64 bytesSent);
    void onTransmissionConnectionEstablished();
    void onTransmissionConnectionLost();

private:
    void setupAudioFormat();
    void writeWavHeader();
    void finalizeWavFile();
    bool initializeAudioCapture(const QString &deviceId);
    bool setupOutputCapture();
    
    // 音频相关
    QAudioSource *m_audioSource;
    QAudioDevice m_audioDevice;
    QAudioFormat m_audioFormat;
    QIODevice *m_audioIODevice;
    
    // 文件相关
    QFile m_outputFile;
    QString m_outputFilePath;
    QBuffer m_audioBuffer;
    
    // 状态
    bool m_isCapturing;
    bool m_useOutputDevice;
    
    // WAV文件信息
    qint64 m_dataSizePosition;
    qint64 m_fileSizePosition;
    qint64 m_dataStartPosition;
    
    // 音频参数
    static const int SAMPLE_RATE = 48000;  // 更新为48kHz
    static const int CHANNEL_COUNT = 2;
    static const int SAMPLE_SIZE = 16;
    
    // 音频传输相关
    AudioTransmitter *m_transmitter;
    bool m_transmissionEnabled;
    QString m_transmissionHost;
    quint16 m_transmissionPort;
};

#endif // AUDIOCAPTURE_H
